import {uSelectMyDevDataStatistic} from './../../api/index'
import {uSelectDevDetailByDevId, uSelectMyDevParamAndStatus} from '@/api/index'
import {uSelectMyDevListByUserId} from '@/api'
import {getStorage, setStorage} from '@/utils/localstoreage'
import Taro from '@tarojs/taro'
import {observable, computed, action} from 'mobx'
import {createContext} from 'react'
class Home {
  /**首页状态 */
  @observable devListShowType: HomeStore.DevListShowType = null
  /**
   * 首页设备列表展现模式
   * @desc 从本地缓存取值，没有值时默认为 single。有值时返回并更新home.devListShowType
   */
  @computed get getDevListShowType(): Device.DevListShowType {
    if (this.devListShowType === null) {
      let typeOflocal = getStorage(
        'homeDevListShowType'
      ) as Device.DevListShowType | null

      if (!typeOflocal) {
        this.changeDevListShowType('single', false)
        return 'single'
      }
      if (typeOflocal !== this.devListShowType) {
        this.changeDevListShowType(typeOflocal, false)
      }
      console.log(`$c${typeOflocal}`, 'color:yellow')

      return typeOflocal
    } else {
      return this.devListShowType
    }
  }

  /**修改首页设备列表展现模式 */
  @action.bound changeDevListShowType(
    val: Device.DevListShowType,
    showModal?: boolean
  ) {
    setStorage('homeDevListShowType', val)
    this.devListShowType = val
    if (showModal || showModal === undefined) {
      Taro.showModal({
        title: '首页卡片变更成功',
        showCancel: false,
        confirmText: '好的',
        cancelColor: '#576b95'
      })
    }
  }

  // @observable bingding: boolean = false
  // /**绑定设备 */
  // @action.bound
  // async bindDev(result: string) {
  //   this.bingding = true
  //   const userId = getStorage('userId')
  //   if (!userId) return

  //   // devGId = await getDevGIdByTestScan(result)// 体验版本二维码截取devGId
  //   let scanParam = getParamByScan(result) // 线上版本二维码截取devGId
  //   if (!scanParam) return
  //   console.log('扫描截取二维码携带参数成功', scanParam)
  //   Taro.showLoading({
  //     title: '添加设备中...'
  //   })

  //   let res = await uBindDev({
  //     devGId: scanParam.devGId,
  //     userId: userId
  //   })

  //   if (res && res.result === 'error') {
  //     Taro.hideLoading()
  //     Taro.showModal({
  //       content: res.msg || '设备添加失败！'
  //     })
  //     this.bingding = false
  //     return
  //   }
  //   this.bingding = false
  //   Taro.hideLoading()
  //   this.updateListDataByType(true, userId)
  // }

  /**设备列表的加载状态 */
  @observable devListLoading: boolean = false
  @action.bound
  startDevListLoading() {
    this.devListLoading = true
    Taro.showLoading({
      title: '加载中...'
    })
  }

  @action.bound
  finishDevListLoading() {
    this.devListLoading = false
    Taro.hideLoading()
  }

  /**设备列表 */
  @observable devList: HomeStore.DevInfo[] | null = []
  @observable simpleDevInfo: HomeStore.SimpleDevInfo | null = {
    devDataStatisticPack: {
      totalCheckWorkHour: 0,
      reportCount: 0,
      exceptionCount: 0,
      standRatio: 0,
      checkResult: '',
      nowDataStatus: null,
      totalCheckCount: 0,
      totalHour: 0,
      totalOffLineCheckHour: 0,
      exceptionCheckCount: 0,
      normalCheckCount: 0
    },
    devList: []
  }

  @computed get currentDevInfo() {
    if (!this.devList?.length) return null
    return this.devList[this.devSwiperCurrent]
  }

  @action.bound
  changeCurrentDevInfo(data: {[key in keyof HomeStore.DevInfo]?: any}) {
    if (!this.devList?.length) return null
    Object.assign(this.devList[this.devSwiperCurrent], data)
  }

  @action.bound
  updateListDataByType({
    isLogin,
    userId,
    bingding = false
  }: {
    isLogin: boolean
    userId: number
    bingding?: boolean
  }) {
    if (bingding) return
    if (!isLogin) return
    if (!userId) return

    this.startDevListLoading()
    if (this.getDevListShowType === 'single') {
      this.getDevList(userId)
    } else if (this.getDevListShowType === 'simpleList') {
      this.getSimpleDevList(userId)
    }
  }

  /**获取首页设备列表 */
  @action.bound
  getDevList(userId: string | number) {
    userId = userId || getStorage('userId')

    uSelectMyDevListByUserId({userId: userId})
      .then(res => {
        let devList = res.data.map(item =>
          Object.assign({devDetailDataList: null}, item)
        )
        this.devList = devList
        this.finishDevListLoading()
        this.initSwiperChange()
      })
      .catch(err => {
        this.devList = null
        this.finishDevListLoading()
        this.initSwiperChange()
      })
  }

  @action.bound
  initSwiperChange() {
    if (!this.devList) {
      this.devSwiperChange(0)
    } else if (this.devSwiperCurrent > this.devList.length - 1) {
      this.devSwiperChange(this.devList.length - 1)
    } else {
      this.devSwiperChange(this.devSwiperCurrent)
    }
  }

  /**获取首页简单设备列表 */
  @action.bound
  getSimpleDevList(userId: string | number) {
    this.startDevListLoading()
    // 获取设备列表
    uSelectMyDevListByUserId({userId})
      .then(res => {
        // 获取报警信息 异常信息 在线时间 水质分析
        uSelectMyDevDataStatistic({userId})
          .then(res1 => {
            // 获取所有设备的状态信息以及检测参数
            uSelectMyDevParamAndStatus({userId: userId})
              .then(res2 => {
                let devList = res.data
                let devDataStatistic = res1.data
                let devParamAndStatus = res2.data
                this.simpleDevInfo = {
                  devDataStatisticPack: devDataStatistic,
                  devList: devList.map(item => {
                    let current = devParamAndStatus.find(
                      item1 => item1.devName === item.devName
                    )
                    return Object.assign(
                      {
                        devDetailDataList: current as Device.SimpleDevDetailData
                      },
                      item
                    )
                  })
                }
                console.log(this.simpleDevInfo)
                this.finishDevListLoading()
              })
              .catch(() => {
                this.simpleDevInfo = null
                this.finishDevListLoading()
              })
          })
          .catch(() => {
            this.simpleDevInfo = null
            this.finishDevListLoading()
          })
      })
      .catch(() => {
        console.log('获取设备列表 失败')
        this.simpleDevInfo = null
        this.finishDevListLoading()
      })
  }

  /**设备列表 滑块视图容器 */
  @observable devSwiperCurrent: number = 0

  /**滑块视图容器切换时 获取当前设备数据 */
  @action.bound
  devSwiperChange(current: number) {
    this.devSwiperCurrent = current
    if (!this.currentDevInfo) return

    let userId = getStorage('userId')
    if (!userId || userId === '0') return

    let devId = this.currentDevInfo.devId
    uSelectDevDetailByDevId({devId, userId})
      .then(res => {
        this.changeCurrentDevInfo({devDetailDataList: res.data})
      })
      .catch(err => {
        this.changeCurrentDevInfo({devDetailDataList: undefined})
      })
  }

  // @observable loadingByloginScan: boolean = false
  // @action.bound
  // loginScan(address: string) {
  //   this.loadingByloginScan = true
  //   const userWeichatId = getStorage('userWeichatId')
  //   if (!userWeichatId) return
  //   toWxScanAuth({address, userWeichatId})
  // }

  // @action.bound
  // handleScan() {
  //   Taro.scanCode({
  //     success: async scan => {
  //       console.log('扫描二维码成功', scan)
  //       let {
  //         result //二维码包含的信息
  //       } = scan // 扫描二维码的回调

  //       let urlParamList = result
  //         .replace(/https:\/\/d.lohand.com:10001\/weixin\/miniprogram\?/, '')
  //         .split('&')
  //         .map(item => item.split('='))

  //       let paramNameList = urlParamList.map(item => item[0])
  //       let paramValueList = urlParamList.map(item => item[1])
  //       for (let i = 0; i < paramNameList.length; i++) {
  //         const paramName = paramNameList[i]
  //         if (paramName === 'webLoginAddress') {
  //           this.loginScan(paramValueList[i])
  //           return
  //         } else {
  //           this.bindDev(result)
  //           return
  //         }
  //       }
  //       console.log(urlParamList)
  //     },
  //     fail: err => {
  //       let {errMsg} = err
  //       if (errMsg.indexOf('cancel') === -1) {
  //         Taro.showModal({
  //           content: '扫描失败,请重试扫描'
  //         })
  //       }
  //       throw err
  //     }
  //   })
  // }
}
const homeStore = createContext(new Home())
export default homeStore
